package com.moranyunxi.www.controller;

import com.moranyunxi.www.entity.ArticleInfoEntity;
import com.moranyunxi.www.entity.ArticleInfoTemp;
import com.moranyunxi.www.entity.BArticleInfoEntity;
import com.moranyunxi.www.pojo.ResultJson;
import com.moranyunxi.www.util.PhantomJsUtil;
import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.By;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@RestController
public class ArticleInfoController {
    @RequestMapping({"/getWeiXinPage"})
    public ResultJson getWeiXinPage(@RequestParam String WeiXinShareLink) throws IOException {
        //先判断是否为空
        String userSendContent = WeiXinShareLink;

        if (StringUtils.isBlank(userSendContent)) {
            return ResultJson.exception("请输入分享内容！");
        }
        if(StringUtils.isNotBlank(userSendContent) && userSendContent.contains("mp.weixin.qq.com")) {
            //BArticleInfoEntity bArticleInfo = WebSpiderThreadUtil.getWeiXinPage(userSendContent.trim().replaceAll("\"",""));
            //BArticleInfoEntity bArticleInfo2 = WebSpiderUtil.getWeiXinPage(userSendContent.trim().replaceAll("\"",""));
            ArticleInfoTemp item = PhantomJsUtil.getWeiXinPage(userSendContent.trim().replaceAll("\"",""));
            BArticleInfoEntity bArticleInfo = new BArticleInfoEntity();
            bArticleInfo.setArticleTitle(item.getArticleTitle());
            bArticleInfo.setArticleDesc(item.getArticleDesc());
            bArticleInfo.setArticleImgUrl(item.getArticleImgUrl());
            bArticleInfo.setArticleContent(item.getArticleContent());

            bArticleInfo.setCreateTime(new Date());
            bArticleInfo.setModifyTime(new Date());
            bArticleInfo.setCreateUser("");
            bArticleInfo.setArticleSource(Integer.valueOf(1));// 文章来源 1-平台添加 2-用户通过公众号添加 3-用户编辑的文章生成自己的文章
            bArticleInfo.setArticleStatus(Integer.valueOf(2));// 文章状态 0-删除 1-正常 2-隐藏
            bArticleInfo.setSpiderProcessStatus(Integer.valueOf(1));
            bArticleInfo.setSType("后台录入");

            bArticleInfo.setArticleLevel(Integer.valueOf(1)); // 经典文章 0-是 1-否
            bArticleInfo.setHtTemplateId(Integer.valueOf(1)); // 经典标题 0-是 1-否
            bArticleInfo.setArticleVersionNum(Integer.valueOf(2)); // 显示类型 0-大图 2- 常规
            bArticleInfo.setHotType(Integer.valueOf(0)); // 热度类型 0-随机 1-自定义

//            this.bArticleInfoService.save(bArticleInfo);
//            Integer resultId = bArticleInfo.getId();
            return ResultJson.ok(bArticleInfo);
        }else{
            return ResultJson.exception("不是微信公众号文章链接！");
        }
    }

    /**
     * 获取 html 的视频地址
     * @param url 链接地址
     * @return
     */
    @RequestMapping("/videoList")
    public ResultJson videoList(@RequestParam String url) {
        final String videoElementPrefixName = "<video";// video 标签前缀
        final String iframeElementPrefixName = "<iframe";// iframe 标签前缀

        List<String> videoLinkList = new ArrayList<>();// 最终结果
        List<Map<String, Object>> videoSource = new ArrayList<>();// 主要用于视频排序

        String pageSource = PhantomJsUtil.getPageSource(url);
        Document document = Jsoup.parse(pageSource);
        Element content = document.select("div#js_content").first();// 解析文本

        // 第一步：解析 video 标签
        int videoOffset = 0;
        Elements videoElements = content.select("video");// video 标签
        if (!videoElements.isEmpty()) {
            for (Element videoElement : videoElements) {
                String src = videoElement.attr("src");// src 属性
                if (StringUtils.isNotBlank(src)) {
                    int index = pageSource.indexOf(videoElementPrefixName, videoOffset);// video 元素的位置

                    Map<String, Object> videoOptions = new HashMap<>();
                    videoOptions.put("index", index);
                    videoOptions.put("src", src.startsWith("//") ? "https:" + src : src);// 以 // 开头的链接，加上 https: 协议头

                    videoSource.add(videoOptions);

                    videoOffset = index + videoElementPrefixName.length();// 偏移量增加
                }
            }
        }

        // 第二步：解析 iframe 标签
        int iframeOffset = 0;
        Elements iframeElements = content.select("iframe");// iframe 标签
        if (!iframeElements.isEmpty()) {
            for (Element iframeElement : iframeElements) {
                String src = iframeElement.attr("src");// src 属性
                if (StringUtils.isNotBlank(src)) {
                    int index = pageSource.indexOf(iframeElementPrefixName, iframeOffset);// iframe 元素的位置

                    Map<String, Object> iframeOptions = new HashMap<>();
                    iframeOptions.put("index", index);
                    iframeOptions.put("src", src.startsWith("//") ? "https:" + src : src);// 以 // 开头的链接，加上 https: 协议头

                    videoSource.add(iframeOptions);

                    iframeOffset = index + iframeElementPrefixName.length();// 偏移量增加
                }
            }
        }

        // 第二步：对结果集排序
        if (!CollectionUtils.isEmpty(videoSource) && videoSource.size() > 0) {
            videoSource.stream().sorted(Comparator.comparing(PhantomJsUtil::getIndexValueInMap)).collect(Collectors.toList())
                    .forEach(info -> {
                        videoLinkList.add(info.get("src").toString());// 存入集合
                    });
        }

        return ResultJson.ok(videoLinkList);
    }

    /**
     * 获取 html 文本
     * @param url
     * @return
     */
    @GetMapping("/getPageSource")
    public ResultJson getPageSource(@RequestParam String url) {
        String pageSource = PhantomJsUtil.getPageSource(url);
//        Document document = Jsoup.parse(pageSource);// 解析文本
//        Element first = document.select("div#js_content").first();
//        return ResultJson.ok(first.toString());
        return ResultJson.ok(pageSource);
    }
}
